package com.truyentranh.modules.truyentranh;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.truyentranh.R;
import com.truyentranh.controls.AdsViewControl;
import com.truyentranh.controls.DataCachedControl;
import com.truyentranh.data.TamDiemDetailModuleData;
import com.truyentranh.main.AdsBussiness;
import com.truyentranh.modules.tamdiem.TamDiemDetailModulesRenderAdapter;
import com.truyentranh.network.APIRequestWorker;
import com.truyentranh.network.Request;
import com.truyentranh.network.RequestListener;
import com.truyentranh.requester.SearchAutoRequester;
import com.truyentranh.requester.SearchTruyenTranhRequester;
import com.truyentranh.utils.Logger;

public class TruyenTranhSearchActivity extends Activity implements OnScrollListener, OnItemClickListener {

	AutoCompleteTextView autoCompleteTextView;
	ArrayList<String> autoData = new ArrayList<String>();
	ArrayAdapter<String> adapter;

	LinearLayout loadingPage = null;
	LinearLayout loadingError = null;
	Button btnSearch = null;

	LinearLayout mainContent = null;
	AdsViewControl prviewTamDiem = null;
	LinearLayout loadingMore = null;
	GridView imageListView = null;

	boolean isLoading = false;
	TamDiemDetailModulesRenderAdapter tamDiemRenderAdapter = null;

	int page = 1;
	@Override
	protected void onCreate(android.os.Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.truyentranh_search_act);

		autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.txtComicNameInput);
		autoCompleteTextView.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				autoData.clear();
//				callAutoTextFromVuiTruyenTranh();
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
			}
		});
		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, autoData);
		autoCompleteTextView.setAdapter(adapter);
		autoCompleteTextView.setThreshold(3);

		btnSearch  = (Button) findViewById(R.id.btnSearch);
		loadingPage = (LinearLayout) findViewById(R.id.loadingpagetamdiem);
		loadingError = (LinearLayout) findViewById(R.id.loadingError);
		loadingMore = (LinearLayout) findViewById(R.id.loadMore);
		loadingError.setVisibility(View.INVISIBLE);

		mainContent = (LinearLayout) findViewById(R.id.mainContent);

		prviewTamDiem = (AdsViewControl) findViewById(R.id.prviewTamDiem);
		imageListView = (GridView) findViewById(R.id.imageListView);

		imageListView.setNumColumns(3);

		TextView textView = (TextView) findViewById(R.id.titleActivity);
		textView.setText("Tìm truyện");

		Button button = (Button) findViewById(R.id.btnMoreFunctions);
		button.setVisibility(View.GONE);

		Button back = (Button) findViewById(R.id.btnBackAcvitity);
		if (back != null) {
			back.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					DataCachedControl.getInstance().clearCached(DataCachedControl.TRUYENTRANH_CATEGORY_DETAIL);
					finish();
				}
			});
		}

		btnSearch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				doSearch();
			}
		});
	}

	void doSearch(){
		
		if(autoCompleteTextView.getText().toString().length() == 0) return;
		
		loadingPage.setVisibility(View.VISIBLE);

		loadingError.setVisibility(View.INVISIBLE);
		loadingMore.setVisibility(View.INVISIBLE);
		loadingError.setVisibility(View.INVISIBLE);
		mainContent.setVisibility(View.INVISIBLE);
		prviewTamDiem.setVisibility(View.INVISIBLE);
		imageListView.setVisibility(View.INVISIBLE);

		isLoading = true;

		SearchTruyenTranhRequester requester = new SearchTruyenTranhRequester(autoCompleteTextView.getText().toString(), page, new RequestListener() {

			@Override
			public void onRequestFailed(String errorMsg, Request request) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onRequestComplete(Request request) {
				SearchTruyenTranhRequester r = (SearchTruyenTranhRequester)request;
				try{
					JSONObject data = r.getData();
					if(data != null){
						if(data.has("data")){
							JSONObject childData = data.getJSONObject("data");
							ArrayList<TamDiemDetailModuleData> requestedDataList = new ArrayList<TamDiemDetailModuleData>();
//							int total = childData.has("total") ? childData.getInt("total") : 0;
							JSONArray jsonArray = childData.has("result") ? childData.getJSONArray("result") : null;
							if(jsonArray != null){
								final int size = jsonArray.length();
								for (int i = 0; i < size; i++) {

									JSONObject datas = jsonArray.getJSONObject(i);

									String title = datas.has(TamDiemDetailModuleData.TITLE) ? datas.getString(TamDiemDetailModuleData.TITLE) : "";
									String avatar = datas.has(TamDiemDetailModuleData.AVATAR) ? datas.getString(TamDiemDetailModuleData.AVATAR) : "";
									String href = datas.has(TamDiemDetailModuleData.HREF) ? datas.getString(TamDiemDetailModuleData.HREF) : "";
									Log.i("onRequestComplete","" + title);
									TamDiemDetailModuleData detailModuleData = new TamDiemDetailModuleData(title, avatar, href);
									requestedDataList.add(detailModuleData);
								}

								fillDatatoGridView(requestedDataList);
							}
						}
					}
				} catch(Exception e){

				}

			}
		});

		APIRequestWorker.getInstance().addAPIRequest(requester);
	}


	void doAdsByServer() {
		AdsBussiness.getInstance().doGetAdsFromServer(this, prviewTamDiem);
	}

	private void onStartUp() {
		loadingPage.setVisibility(View.GONE);
		loadingError.setVisibility(View.GONE);
		loadingMore.setVisibility(View.GONE);

		loadingError.setVisibility(View.INVISIBLE);
		mainContent.setVisibility(View.INVISIBLE);
		prviewTamDiem.setVisibility(View.INVISIBLE);
		imageListView.setVisibility(View.INVISIBLE);
	}

	void fillDatatoGridView(final ArrayList<TamDiemDetailModuleData> requestedDataList) {

		if (imageListView != null) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					if (tamDiemRenderAdapter == null) {
						tamDiemRenderAdapter = new TamDiemDetailModulesRenderAdapter(TruyenTranhSearchActivity.this, 1, 1, requestedDataList);
						imageListView.setAdapter(tamDiemRenderAdapter);
					} else {
						tamDiemRenderAdapter.setBlockList(requestedDataList);
						tamDiemRenderAdapter.notifyDataSetChanged();
					}

					imageListView.setOnItemClickListener(TruyenTranhSearchActivity.this);
					imageListView.setOnScrollListener(TruyenTranhSearchActivity.this);

					loadingPage.setVisibility(View.GONE);
					loadingError.setVisibility(View.GONE);
					loadingMore.setVisibility(View.GONE);

					mainContent.setVisibility(View.VISIBLE);
					prviewTamDiem.setVisibility(View.VISIBLE);
					imageListView.setVisibility(View.VISIBLE);

					isLoading = false;

					doAdsByServer();
				}
			});

		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
		Logger.logMe("1");
		if (tamDiemRenderAdapter != null) {
			Logger.logMe("2");
			TamDiemDetailModuleData diemMetalData = tamDiemRenderAdapter.getItem(index);
			Logger.logMe("3");

			final String href = diemMetalData.getHref();
			if (href != null && !"".equals(href)) {

				finish();

				Intent intent = new Intent(getApplication(), TruyenTranhChapterListActivity.class);
				intent.putExtra("href", href);
				intent.putExtra("NAME", diemMetalData.getTitle());
				intent.putExtra("AVATAR", diemMetalData.getAvatar());
				startActivity(intent);
			}
		}
	}


	void callAutoTextFromVuiTruyenTranh() {
		SearchAutoRequester autoRequester = new SearchAutoRequester(autoCompleteTextView.getText().toString(), new RequestListener(){

			@Override
			public void onRequestComplete(Request request) {
				Log.i("onRequestComplete", "onRequestComplete");
				if(request instanceof SearchAutoRequester){
					SearchAutoRequester r = (SearchAutoRequester)request;
					try {
						adapter.clear();
						JSONArray array = r.getData();
						for (int i = 0, n = array.length(); i < n; i++) {
							adapter.add(array.getString(i));
							Log.i(">>>", ""+array.getString(i));
						}
						adapter.notifyDataSetChanged();

						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								autoCompleteTextView.showDropDown();
							}
						});

					} catch (Exception e) {

					}

				}


			}

			@Override
			public void onRequestFailed(String errorMsg, Request request) {
				// TODO Auto-generated method stub

			}


		});

		APIRequestWorker.getInstance().addAPIRequest(autoRequester);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		onStartUp();
	}

	RequestListener listenerLoadMore = new RequestListener() {

		@Override
		public void onRequestFailed(String errorMsg, Request request) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					if (loadingMore != null && loadingMore.getVisibility() != View.GONE)
						loadingMore.setVisibility(View.GONE);
				}
			});

		}

		@Override
		public void onRequestComplete(Request request) {
			if (request instanceof SearchTruyenTranhRequester) {

				SearchTruyenTranhRequester r = (SearchTruyenTranhRequester) request;

				final ArrayList<TamDiemDetailModuleData> requestedDataList = new ArrayList<TamDiemDetailModuleData>();
				try {
					JSONObject jsonObject = r.getData();

					JSONArray jsonArray = jsonObject.getJSONArray("data");
					final int size = jsonArray.length();
					for (int i = 0; i < size; i++) {
						JSONObject datas = jsonArray.getJSONObject(i);

						String title = datas.has(TamDiemDetailModuleData.TITLE) ? datas.getString(TamDiemDetailModuleData.TITLE) : "";
						String avatar = datas.has(TamDiemDetailModuleData.AVATAR) ? datas.getString(TamDiemDetailModuleData.AVATAR) : "";
						String href = datas.has(TamDiemDetailModuleData.HREF) ? datas.getString(TamDiemDetailModuleData.HREF) : "";

						TamDiemDetailModuleData detailModuleData = new TamDiemDetailModuleData(title, avatar, href);
						requestedDataList.add(detailModuleData);
					}
				} catch (Exception e) {

				}

				if (imageListView != null) {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							if (tamDiemRenderAdapter != null) {

//								ArrayList<TamDiemDetailModuleData> cachedList = (ArrayList<TamDiemDetailModuleData>) DataCachedControl.getInstance().getCached(DataCachedControl.TRUYENTRANH_CATEGORY_DETAIL);
//								if (cachedList != null && requestedDataList != null) {
//									final int size = requestedDataList.size();
//									for (int i = 0; i < size; i++) {
//										cachedList.add(requestedDataList.get(i));
//									}
//								}
								tamDiemRenderAdapter.appendData(requestedDataList);
							}

							if(!requestedDataList.isEmpty())
								isLoading = false;

							if (loadingMore != null && loadingMore.getVisibility() != View.GONE)
								loadingMore.setVisibility(View.GONE);
						}
					});

				}
			}

		}
	};

	@Override
	public void onScroll(AbsListView arg0, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//		int lastInScreen = firstVisibleItem + visibleItemCount;
//		if (!isLoading && tamDiemRenderAdapter != null && !tamDiemRenderAdapter.isEmpty() && (lastInScreen == totalItemCount) && (page < 100)) {
//			if (loadingMore != null && loadingMore.getVisibility() != View.VISIBLE)
//				loadingMore.setVisibility(View.VISIBLE);
//			isLoading = true;
//			page += 1;
//
//			SearchTruyenTranhRequester requester = new SearchTruyenTranhRequester(autoCompleteTextView.getText().toString(), page, listenerLoadMore);
//			APIRequestWorker.getInstance().addAPIRequest(requester);
//		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}

}
